#include <QMouseEvent>
#include "table-view.h"
#include "hierarchical-header-view.h"


TableView::TableView (QWidget *parent) :
    QTableView(parent), m_pressedMouseButton(Qt::NoButton)
{
    setHierarchicalHeaderEnabled(false);
}


bool TableView::isHierarchicalHeaderEnabled() const
{
    return !m_hierarchicalHeaderView.isNull();
}


HierarchicalHeaderView* TableView::hierarchicalHeader() const
{
    return m_hierarchicalHeaderView.data();
}


Qt::MouseButtons TableView::pressedMouseButton() const
{
    return m_pressedMouseButton;
}


void TableView::setHierarchicalHeaderEnabled (bool enable)
{
    // if we should enable and hierarchical header view exists, return
    // also, when we should disable and there is no hierarchical header, return
    if (enable == !m_hierarchicalHeaderView.isNull())
        return;

    if (enable)
    {
        Q_ASSERT(m_hierarchicalHeaderView.isNull());
        m_hierarchicalHeaderView = new HierarchicalHeaderView(Qt::Horizontal, this);
        m_hierarchicalHeaderView.data()->setSectionsClickable(true);
        m_hierarchicalHeaderView.data()->setHighlightSections(true);
        setHorizontalHeader(m_hierarchicalHeaderView.data());
    }
    else
    {
        QHeaderView* headerView = new QHeaderView(Qt::Horizontal, this);
        headerView->setSectionsClickable(true);
        headerView->setHighlightSections(true);
        setHorizontalHeader(headerView);
    }
}


void TableView::columnCountChanged (int oldCount, int newCount)
{
    QTableView::columnCountChanged(oldCount, newCount);

    // fix selection when entire rows should be selected and columns have been added
    if (selectionBehavior() == QTableView::SelectRows && selectionModel() && selectionModel()->hasSelection()
        && oldCount < newCount)
    {
        QModelIndexList indexes = selectionModel()->selectedIndexes();
        Q_ASSERT(!indexes.isEmpty());
        qSort(indexes);
        QList<int> selectedRows;

        for (int i = 0; i < indexes.size(); i += oldCount)
            selectedRows.append(indexes.at(i).row());

        for (int i = 0; i < selectedRows.size(); i++)
            selectRow(selectedRows.at(i));
    }
}


void TableView::mousePressEvent (QMouseEvent *event)
{
    m_pressedMouseButton = event->buttons();
    return QTableView::mousePressEvent(event);
}
